﻿#region Copyright Notice
// 
// 
// Copyright (c) 2009-2010 Anindya Chatterjee
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// 
// 
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using Event.Plugin;
using Event.Plugin.Configuration;
using GCodeIssueTracker;
using GCore;

namespace DesktopNotifier.Utility
{
    public partial class BugReport : KryptonForm
    {
        private static readonly string Separator = Environment.NewLine +
                                                   "========================================================" +
                                                   Environment.NewLine;

        private readonly AppConfig _config;
        private readonly IEvent _sender;

        public BugReport(IEvent sender, AppConfig config)
        {
            InitializeComponent();
            _sender = sender;
            _config = config;
        }

        public Exception Bug { get; set; }

        private void BugReport_Load(object sender, EventArgs e)
        {
            if (Bug != null)
            {
                bugTextBox.AppendText(GenerateErrorReport());
            }
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bugTextBox.SelectAll();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bugTextBox.Copy();
        }

        private void bugButton_Click(object sender, EventArgs e)
        {
            try
            {
                var glogin = new GAccountLogin {StartPosition = FormStartPosition.CenterScreen};
                if (glogin.ShowDialog() == DialogResult.OK)
                {
                    var service = new ProjectHostingService("ozone-desktop-notifier", glogin.GUserName, glogin.GPassword);
                    if (_config.UseProxy)
                        service.ProxySettings = _config.Proxy;

                    var issue = new IssuesEntry
                                    {
                                        Author = new Author {Name = glogin.GUserName},
                                        Ccs = new List<Cc> {new Cc {UserName = "anidotNet"}},
                                        Status = "New",
                                        Title = (Bug != null) ? Bug.Message : "Error Report",
                                        Content = new Content
                                                      {
                                                          Description =
                                                              "Steps to recreate : \n\n" + stepsTextBox.Text +
                                                              Separator + GenerateErrorReport(),
                                                          Type = "text"
                                                      }
                                    };

                    IssuesEntry result = service.SubmitNewIssue(issue, "ozone-1");
                    if (result != null)
                        MessageBox.Show("The Bug has been submitted sucessfully.\nThe id of the issue is " + result.Id);
                    else
                    {
                        MessageBox.Show("There is some problem in bug submission.\nSwitching to manual mode.");
                        Process.Start(Constants.BugReportUrl);
                    }
                }
                else
                {
                    MessageBox.Show("You have not opted for automatic submission.\nSwitching to manual mode.");
                    Process.Start(Constants.BugReportUrl);
                }
            }
            catch
            {
                MessageBox.Show("There is some problem in bug submission.\nSwitching to manual mode.");
                Process.Start(Constants.BugReportUrl);
            }
        }

        private void manualBugButton_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(Constants.BugReportUrl);
            }
            catch
            {
            }
        }

        private string GenerateErrorReport()
        {
            if (Bug != null)
            {
                string message = "Exception Message : " + Environment.NewLine + Environment.NewLine + Bug.Message +
                                 Separator;
                string inner = (Bug.InnerException != null)
                                   ? "Inner Exception : " + Environment.NewLine + Environment.NewLine +
                                     Bug.InnerException.Message + Separator
                                   : "";
                string stacktrace = "Stack Trace : " + Environment.NewLine + Environment.NewLine + Bug.StackTrace +
                                    Separator;
                string sender = (_sender != null)
                                    ? "Source : " + Environment.NewLine + Environment.NewLine + _sender.Name + Separator
                                    : "";
                string result = sender + message + inner + stacktrace;

                var fs = new FileStream(Constants.LogPath, FileMode.Create);
                var sw = new StreamWriter(fs);
                sw.WriteLine(result);
                sw.Close();
                fs.Close();

                return result;
            }
            return "";
        }
    }
}